package cn.itcast.service.impl;

import cn.itcast.dto.ChatDTO;
import cn.itcast.service.ChatService;
import cn.itcast.tool.SetTool;
import com.google.errorprone.annotations.Var;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

/**
 * @author shd
 * @version V1.0
 * @date 2025-04-21 1:04
 */
@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {
    private final ChatClient chatClient;
    private final SetTool setTool;
    private final VectorStore vectorStore;

    @Override
    public Flux<String> streamChat(ChatDTO chatDTO) {
        SearchRequest searchRequest = SearchRequest.builder().query(chatDTO.getQuestion())
                .topK(1)
                .build();


        return chatClient.prompt()
                .advisors(advisorSpec -> advisorSpec
                        .advisors(new QuestionAnswerAdvisor(vectorStore, searchRequest))
                        .param( AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatDTO.getSessionId()))
                .tools(setTool)
                .user(chatDTO.getQuestion())
                .stream()
                .content()
                .concatWith(Flux.just("[END]"));
    }
}
